;
(function(w) {

  new Vue({
    el: '#businessMange',
    data: {
      quanxian: JSON.parse(localStorage.getItem('permissions')),
      listMenu: [
        {
          name: '未跟进过',
          num: 0,
          code: 'FMWF'
        },
        {
          name: '跟进中',
          num: 0,
          code: 'FMFI'
        },
        {
          name: '逾期未跟进',
          num: 0,
          code: 'FMOWF'
        },
        {
          name: '已关闭',
          num: 0,
          code: 'FMGB'
        },
        {
          name: '已转客户',
          num: 0,
          code: 'FMTC'
        }
      ],
      selectedListMenuCode: [],
      totalPage: 0,
      totalCount: 0,
      currentPage: 1,
      pageCount: ['10'],
      pageCounts: [
      {
        name: '10',
        code: '10'
      },
      {
        name: '15',
        code: '15'
      },
      {
        name: '20',
        code: '20'
      }
      ],
      orders: '',
      columns: '',
      data: {},
      keyword: '',
      importFlag: false,
      dockpeople: [], //对接人
      dockVal: '',
      channelType: [], //渠道分类
      channerCode: [],
      channerName: [], //渠道名称
      channerNameCode: [],
      source: [], //商机来源
      sourceCode: [],
      through: false,
      notThrough: false,
      detection: false, //检测
      lutFlag: '1',
      putFlag: '1',
      through: false,
      notThrough: false,
      detection: false, //检测
      detectionBtn: true,
      isShowDownload: false,
      is500: false,
      srcUrl: '',
      isExtenseFlag: false,
      listObj: {},
      //自定义开始
      configType: 'WZ', //默认完整WZ     JD简单，WZ完整，自定义配置PZ
      module: '#',
      headArr: [],
      sortTableTitle: [],
      isScroll: false,
      isShowTableLayer: false,
      dateTimeUpdate: [],
      isActiveCode: '#',
      leftWidth: 0,
      rightWidth: 0,
      leftTableArr: [],
      rightTableArr: [],
      tbTitleWidth: {},
      lefthover: 0,
      tophover: 0,
      texthover: false,
      textLong: '',
			industryType: [],
      selectedIndustryType: [],
      secondRowBeginDate:'',
      secondRowEndDate:''
    },
    filters: {
      indexAdd(i) {
        return Number(i) < 10 ? '0' + (i + 1) : i;
      },
      formatDate(time) {
        if (time === undefined) {
          return '--'
        }
        var date = new Date(time)
        return hlDateUtil.formatUTCDate(date, 'yyyy-MM-dd')
      },
      formatYYYYMMddHHmm(item) {
        if (!item) return '--'
        return hlDateUtil.formatUTCDate(item, 'yyyy-MM-dd HH:mm')
      },
      stateReturn(str) {
        var result;
        switch (str) {
          case 'FMWF':
            result = '未跟进过'
            break;
          case 'FMFI':
            result = '跟进中'
            break;
          case 'FMOWF':
            result = '逾期未跟进'
            break;
          case 'FMGB':
            result = '已关闭'
            break;
          case 'FMTC':
            result = '已转客户'
            break;
          default:
            result = '--'
        }
        return result
      },
      formatUndefinedFB(item) {
        if (!item) return '--'
        if (typeof item == 'number') {
          if (!isNaN(item) && item.toString().length == 13) {
            return hlDateUtil.formatUTCDate(item, 'yyyy-MM-dd HH:mm')
          };
        }
        return item
      },
    },
    methods: {
      selectMenuList() {
        this.currentPage = 1
        this.getListData()
      },
      //获取线索来源
      setSourceCode(arr) {
        this.sourceCode = [arr[0].code]
      },
      //显示hover
      hoverText(e, v) {
        var s = this.$refs.scrollLeft.scrollLeft;
        var l = e.srcElement.parentNode.offsetLeft - s;
        var t = e.srcElement.parentNode.offsetTop + 40

        this.lefthover = l + 'px';
        this.tophover = t + 'px';
        this.texthover = true;
        this.textLong = v;
      },
      mouseleaveOut() {
        this.lefthover = 0 + 'px';
        this.tophover = 0 + 'px';
        this.texthover = false;
        this.textLong = '';
      },
      //去详情
      goTodetail(id) {
        hlUrlUtil.goTo('businessDetails', {
          'businessId': id,
          'page': 'mySiness',
          'ddtab': true
        }, true)
      },
      resetTabbar() {
        this.selectedListMenuCode = [];
        this.getListData()
      },
      //新建
      createSj() {
        hlUrlUtil.goTo('businessCreate', {
          page: 'mySiness',
          ddtab: true
        }, true)
      },
      //渠道分类
      getSJCHANNELCATE() {
        hlhttp.get({
          url: 'configure/dict',
          data: { module_code: 'ZHSH', config_name: 'ZS_CHANNEL_CATE'},
          success: res => {
            this.channelType = hlArrayUtil.replaceData(res, [{
              key: 'dictName',
              rKey: 'name'
            }, {
              key: 'dictCode',
              rKey: 'code'
            }]);
          }
        })
      },
      //渠道名称
      getSJCHANNELNAME() {
        hlhttp.get({
          url: 'configure/dict',
          data: {
            module_code: 'ZHSH',
            config_name: 'ZS_CHANNEL_NAME',
            parent_dict_code: this.channerCode[0]
          },
          success: res => {
            this.channerName = hlArrayUtil.replaceData(res, [{
              key: 'dictName',
              rKey: 'name'
            }, {
              key: 'dictCode',
              rKey: 'code'
            }]);
          }
        })
      },
      //set渠道分类
      setSJCHANNELCATE(arr) {
        this.channerCode = [arr[0].code];
        this.getSJCHANNELNAME()
      },
      //set渠道mingc
      setChannerNameCode(arr) {
        this.channerNameCode = [arr[0].code];
      },
      //商机来源
      getSJsource() {
        hlhttp.get({
          url: 'configure/dict',
          data: {
            module_code: 'ZHSH0SHJI',
            config_name: 'SJ_SOURCE'
          },
          success: res => {
            this.source = hlArrayUtil.replaceData(res, [{
              key: 'dictName',
              rKey: 'name'
            }, {
              key: 'dictCode',
              rKey: 'code'
            }]);
          }
        })
      },
      //获取data
      getListData() {
        const self = this
        var beginDate = this.secondRowBeginDate? this.secondRowBeginDate + ' 00:00:00' : '#'
        var endDate = this.secondRowEndDate ? this.secondRowEndDate + ' 23:59:59' : '#'

        var data = {
          "origin": self.sourceCode.length ? self.sourceCode[0] : '#',
          "channel_category_code": self.channerCode.length ? self.channerCode[0] : '#',
          "channel_name_code": self.channerNameCode.length ? self.channerNameCode[0] : '#',
          "status": self.selectedListMenuCode.length ? self.selectedListMenuCode.toString() : '#',
					'industry': self.selectedIndustryType.length ? self.selectedIndustryType + '' : '#',
          "keyword": self.keyword || '#',
          "followup_time_begin": beginDate,
          "followup_time_end": endDate,
          "limit": self.pageCount[0],
          "page": self.currentPage,
          "columns": self.columns || '#',
          "orders": self.orders || '#'
        }

        hlhttp.get({
          url: 'customer/biz_oppt_user_search',
          data: data,
          success: res => {
            res.biz_oppts.map(item => {
              if (!item.followupRecords.length) {
                item.followupRecords.push({})
              }
            })

            self.totalCount = res.totalCount
            self.totalPage = res.totalPage
            self.listObj = res;
            self.listMenu[0].num = res.countInfo.FMWF;
            self.listMenu[1].num = res.countInfo.FMFI;
            self.listMenu[2].num = res.countInfo.FMOWF;
            self.listMenu[3].num = res.countInfo.FMGB;
            self.listMenu[4].num = res.countInfo.FMTC;
          }
        })
      },
      setMoreNum(arr) {
        this.pageCount = [arr[0].code];
        this.getListData()
      },
      //重置
      resetData() {
        this.orders = '';
        this.isActiveCode = '';
        this.columns = '';
        this.sourceCode = [];
        this.channerCode = [];
        this.channerNameCode = [];
				this.selectedIndustryType = []
        this.keyword = '';
        this.pageCount = ['10'];
        this.currentPage = 1;
        this.secondRowBeginDate = ''
        this.secondRowEndDate = ''
        this.getListData()
      },
      //查询
      search() {
        this.currentPage = 1;
        this.pageCount = ['10'];
        this.getListData();
      },
      //导入
      importExcl() {
        this.importFlag = true;
      },
      //关闭
      importExclClose() {
        this.importFlag = false;
        this.detection = false;
        this.notThrough = false;
        this.detectionBtn = true;
        this.through = false;
        this.srcUrl = '';
        $('.filename-i').val('')
      },
      //上传模板
      downloadxslc() {
        $('.upload-filess').trigger('click')
        this.detection = false;
        this.notThrough = false;
        this.detectionBtn = true;
        this.through = false;
        this.srcUrl = '';
        $('.filename-i').val('')
      },
      //jian ce
      detectionXslx() {
        this.detection = true;
        this.detectionBtn = false;
        if (!this.srcUrl) return;

        hlhttp.put({
          baseUrl: exclUrl,
          url: 'resource/opportunity_check',
          data: {
            file_name: this.srcUrl
          },
          success: res => {
            if (res.code == 200) {
              this.detection = false;
              this.notThrough = false;
              this.detectionBtn = false;
              this.through = true;
              this.isShowDownload = true;
              this.is500 = false;
            }
            if (res.code == 400) {
              this.detection = false;
              this.notThrough = true;
              this.detectionBtn = false;
              this.is500 = false;
              this.through = false;
              this.isShowDownload = true;
              this.srcUrl = res.url
            }
            if (res.code == 500) {
              this.is500 = true;
              this.detection = false;
              this.notThrough = false;
              this.detectionBtn = false;
              this.through = true;
              this.srcUrl = res.url;
              this.isShowDownload = true;
            }
          },
          error: res => {
            hl.toast('请使用标准模板上传！')
            this.detection = false;
            this.notThrough = true;
            this.detectionBtn = false;
            this.isShowDownload = false;
            this.through = false;
          }
        })
      },
      //submit xslc
      submibXslc() {
        hlhttp.post({
          baseUrl: exclUrl,
          url: 'resource/opportunity_upload_data',
          data: {
            file_name: this.srcUrl,
            is_myself: 'Y'
          },
          success: () => {
            hl.toast('上传成功')
            this.getListData()
            this.importExclClose()
          }
        })
      },
      //更新时间
      sortBySTTime(item) {
        if (this.dateTimeUpdate.indexOf(item.value) == -1) return
        this.isActiveCode = item.value;
        this.orders = this.orders == 'ASC' ? 'DESC' : 'ASC';
        this.columns = item.orderName
        this.getListData()
      },
      //获取自定义表头配置状态
      configTypeDt() {
        hlhttp.get({
          url: 'configure/customize_column_header/type',
          data: {
            module: 'ZHSH_WDXS'
          },
          success: (data) => {
            this.configType = data.configType;
            this.customizeHeaderDt()
          }
        })
      },
      //获取自定义表头配置信息
      customizeHeaderDt() {
        hlhttp.get({
          url: 'configure/customize_column_header',
          data: {
            module: 'ZHSH_WDXS'
          },
          success: (data) => {
            data.customConfigList.map(item => {
              item.seq = Number(item.seq)
              item.customSeq = Number(item.customSeq)
              item.isActive = 'N'
              if (item.orderFlag == 'Y') {
                this.dateTimeUpdate.push(item.value)
              }
            })
            if (this.configType == 'JD' || this.configType == 'WZ') {
              data.customConfigList = data.customConfigList.sort(hlArrayUtil.compareAsc('seq'))
            }
            if (this.configType == 'PZ') {
              data.customConfigList = data.customConfigList.sort(hlArrayUtil.compareAsc('customSeq'))
            }

            this.headArr = JSON.parse(JSON.stringify(data.customConfigList));
            this.sortTableTitle = JSON.parse(JSON.stringify(data.customConfigList));
            this.lrTable()
          }
        })
      },
      //左右表格table
      lrTable() {
        this.leftWidth = 0;
        this.rightWidth = 0;
        this.leftTableArr = [];
        this.rightTableArr = [];

        this.headArr.map(item => {
          if (this.configType == 'JD') {
            if (item.baseFlag == 'Y') {
              this.lrTableDistinguish(item)
            }
          }
          if (this.configType == 'WZ') {
            this.lrTableDistinguish(item)
          }
          if (this.configType == 'PZ') {
            if (item.customShowFlag == 'Y') {
              this.lrTableDistinguish(item)
            }
          }
        })
        this.tbTitleWidthCalculation()
      },
      //左右表格区分
      lrTableDistinguish(item) {
        switch (item.unionTablePart) {
          case '1':
            this.leftTableArr.push(item)
            break;
          case '2':
            this.rightTableArr.push(item)
            break;
          default:
            break;
        }
      },
      //宽度计算
      tbTitleWidthCalculation() {

        this.leftTableArr.map(item0 => {
          this.leftWidth += Number(item0.styleWidth)
        })
        this.rightTableArr.map(item0 => {
          this.rightWidth += Number(item0.styleWidth)
        })
        this.tbTitleWidth = {
          width: (this.leftWidth + this.rightWidth) + 'px'
        }
        if (this.leftWidth + this.rightWidth < 960) {
          this.leftWidth = '50%'
          this.rightWidth = '50%'
          this.tbTitleWidth = {
            width: '100%'
          }
        }

      },
      //弹窗显示
      showTableLayer() {
        this.isShowTableLayer = true;
      },
      //关闭自定义表头弹窗
      closeTableLayer() {
        this.isShowTableLayer = false;
      },
      //简单完整配置切换
      selectTableType(type) {
        this.configType = type;
        this.changeTableType(type)
        this.updateConfigType()
      },
      //更新自定义表头配置状态
      updateConfigType() {
        hlhttp.put({
          url: 'configure/customize_column_header/type',
          data: {
            module: 'ZHSH_WDXS',
            config_type: this.configType
          },
          success: () => {
            this.configTypeDt()
          }
        })
      },
      //改变头部
      changeTableType(type) {
        if (type == 'JD' || type == 'WZ') {
          this.headArr = this.headArr.sort(hlArrayUtil.compareAsc('seq'))
        }
        if (type == 'PZ') {
          this.headArr = this.headArr.sort(hlArrayUtil.compareAsc('customSeq'))
        }
        this.tbTitleWidthCalculation()
      },
      //显示某个自定义标题
      selectedTitleItem(i) {
        this.sortTableTitle[i].customShowFlag = 'Y'
      },
      //关闭某个自定义标题
      cancelSelectedTitleItem(i) {
        this.sortTableTitle[i].customShowFlag = 'N'
      },
      showhighLightTitleItem(el, i) {
        this.sortTableTitle[i].isActive = 'Y'
      },
      removehighLightTitleItem(el, i) {
        this.sortTableTitle[i].isActive = 'N'
      },
      //鼠标经过显示scroll
      showScroll() {
        this.isScroll = true;
      },
      //鼠标离开关闭scroll
      hideScroll() {
        this.isScroll = false;
      },
      // 确定提交自定义表格
      confirmSubmitTable() {
        let dataArr = [];
        this.sortTableTitle.map((item, index) => {
          dataArr.push({
            "base_flag": item.baseFlag,
            "seq": item.seq,
            "custom_show_flag": item.customShowFlag,
            "custom_seq": index,
            "custom_display_name": item.customDisplayName ? item.customDisplayName : '#',
            "dict_code": item.dictCode,
            "config_type": item.configType,
            "name": item.name,
            "value": item.value,
            "union_table_part": item.unionTablePart,
            flex: item.flex,
            style_width: item.styleWidth,
            order_flag: item.orderFlag,
            order_name: item.orderName
          })
        })
        hlhttp.put({
          url: 'configure/customize_column_header',
          data: {
            module: 'ZHSH_WDXS',
            custom_config: JSON.stringify(dataArr)
          },
          success: (data) => {
            hl.toast('操作成功')
            this.closeTableLayer()
            this.updateConfigType()
          }
        })
      },
      // 初始化拖动排序
      initSortable() {
        const self = this;
        const el = document.getElementById('sortableTable');
        Sortable.create(el, {
          draggable: 'ul',
          onEnd(evt) {
            const beginIndex = evt.oldIndex;
            const endIndex = evt.newIndex;
            const newArr = JSON.parse(JSON.stringify(self.sortTableTitle));
            if (self.sortTableTitle[beginIndex].unionTablePart == self.sortTableTitle[endIndex].unionTablePart) {
              newArr.splice(endIndex, 0, newArr.splice(beginIndex, 1)[0])
            } else {
              hl.toast('合并表格无法跨表头排序')
            }
            self.sortTableTitle = [];
            self.$nextTick(() => {
              self.sortTableTitle = newArr
            })
          }
        })
      },
			// 获取产业
			getIndustryType() {
			  hlhttp.get({
			    url: 'configure/industry/dict',
			    success: data => {
			      data.unshift({
			        'dictName': '全部',
			        'dictCode': '#'
			      })
			      this.industryType = hlArrayUtil.replaceData(data, [{ key: 'dictName', rKey: 'name' }, { key: 'dictCode', rKey: 'code' }]);
			    }
			  })
			},
    },
    mounted: function() {
      hlSelectUi()
      this.getSJsource()
      this.getSJCHANNELCATE()
      this.getListData()
      this.initSortable()
      this.configTypeDt()
			this.getIndustryType()

      fileUpload('.upload-filess', uploadUrl, (src) => {
        if (src.json == undefined) return;
        if (!(src.json.name.indexOf('xls') > -1)) {
          hl.toast('请上传正确的模板')
          return
        }
        if (!(src.json.name.indexOf('xlsx') > -1)) {
          hl.toast('请上传正确的模板')
          return
        }
        this.srcUrl = src.json.url.substr(src.json.url.lastIndexOf('/') + 1);
        $('.filename-i').val(src.json.name)
      })
    }
  })

}(window))
